<?php
declare (strict_types = 1);

namespace app\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\model\relation\BelongsToMany;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    public function getMobileAttr($value): array|string
    {
        // 隐藏手机号中间四位
        return substr_replace($value, '****', 3, 4);
    }
    public function enterprises(): BelongsToMany
    {
        return $this->belongsToMany(
            Enterprise::class,
            'enterprise_member',
            'enterprise_id',
            'user_id'
        );
    }
    public function getUserEnterprises(int $use_id): array
    {
        try {
            $user = $this->find($use_id);
            $enterprises = $user->enterprises()->select();
            $enterpriseData = [];
            foreach ($enterprises as $enterprise) {
                $role = (new Role)->find($enterprise->pivot->role_id);
                $enterpriseData[] = [
                    'id' => $enterprise->id,
                    'name' => $enterprise->name,
                    'avatar' => $enterprise->avatar,
                    'role_id' => $enterprise->pivot->role_id,
                    'role_style'=> $role ? $role->style : '',
                    'role_name' => $role ? $role->role_name : '未知角色',
                    'is_default' => $enterprise->pivot->is_default,
                    'join_time' => $enterprise->pivot->join_time
                ];
            }
            return $enterpriseData;
        } catch (DataNotFoundException|ModelNotFoundException|DbException) {
            return [];
        }
    }
    public function getUserDefaultEnterprise(int $use_id): array
    {
        try {
           $enterpriseMember = (new EnterpriseMember())
               ->where('user_id', $use_id)
               ->where('is_default', 1)
               ->find()->toArray();
           $role = (new Role)->find($enterpriseMember['role_id'])->toArray();
           $enterprise = (new Enterprise)->find($enterpriseMember['enterprise_id'])->toArray();
           return [
                'id' => $enterprise['id'],
                'name' => $enterprise['name'],
                'avatar' => $enterprise['avatar'],
                'role_id' => $enterpriseMember['role_id'],
                'role_style'=> $role ? $role['style'] : '',
                'role_name' => $role ? $role['role_name'] : '未知角色',
                'is_default' => $enterpriseMember['is_default'],
                'join_time' => $enterpriseMember['join_time'],
                'permissions' => $role['permissions']
           ];
        } catch (DataNotFoundException|ModelNotFoundException|DbException) {
            return [];
        }
    }
}
